package com.zd.shopping.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.LogoPosition;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.zd.shopping.R;
import com.zd.shopping.apis.DeliverGoodsApi;
import com.zd.shopping.bean.WmTmsNoticeHEntity;
import com.zd.shopping.utils.MyDialogUtils;
import com.zd.shopping.utils.RouterUtils;
import com.zd.shopping.widget.GeoHasher;
import com.zd.shopping.widget.InfoView;
import com.zwz.mall.api.OnRequestListener;
import com.zwz.mall.base.BaseActivity;
import com.zwz.mall.utils.BarHeightUtils;
import com.zwz.mall.utils.ToastUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

/**
 * @author Administrator
 * @date 2019/10/30 0030
 */

public class DeliverGoodsDtActivity extends BaseActivity  implements MyDialogUtils.OnCenterItemClickListener {
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.fake_status_bar)
    View fakeStatusBar;
    @BindView(R.id.mapView)
    MapView mMapView;
    private BaiduMap mBaiduMap;
    private List<LatLng> latLngsList;
    private List<LatLng> latLngsAllList=new ArrayList<> ();
    private  List<String>  allId=new ArrayList<> ();
    private MarkerOptions option;
    private List<Double> latitudeList = new ArrayList<Double> ();
    private List<Double> longitudeList = new ArrayList<Double> ();
    private double maxLatitude;
    private double minLatitude;
    private double maxLongitude;
    private double minLongitude;
    private double distance;
    private float level;
    private LatLng center;
    private InfoWindow infoWindow;
    private double reMember;
    private double reCarno;
    private  List<String>  reMembers=new ArrayList<> ();
    private  List<String>  reCarnos=new ArrayList<> ();
    private String delvAddr;
    private DeliverGoodsApi deliverGoodsApi = new DeliverGoodsApi ();
    private MyDialogUtils myDialogUtils;
    private String reCarnosId;
    private String reMembersId;
    @Override
    public int getLayoutId() {
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        return R.layout.activity_delivergoodsdt;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy ();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
//        mMapView.onDestroy ();
    }

    @Override
    protected void onResume() {
        super.onResume ();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume ();
    }

    @Override
    protected void onPause() {
        super.onPause ();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause ();
    }

    @Override
    public void initView() {
        BarHeightUtils.setStatusBarHeight (fakeStatusBar, getStatusBarHeight ());
        title.setText ("送货地图");
        deliverGoodsApi.username = user.getUsername ();
//        deliverGoodsApi.searchstr = "送货";
        mBaiduMap = mMapView.getMap ();
        //普通地图
        mBaiduMap.setMapType (BaiduMap.MAP_TYPE_NORMAL);
//        开启交通图
        mBaiduMap.setTrafficEnabled(true);

        //设置logo位置,默认在左下角显示，不可以移除。使用枚举类型控制显示的位置，共支持6个显示位置(左下，中下，右下，左上，中上，右上)。
        mMapView.setLogoPosition (LogoPosition.logoPostionleftBottom);


    }

    private void intData() {
        if (deliverGoodsApi.isLoading ()) {
            return;
        }
        deliverGoodsApi.list.clear ();
        deliverGoodsApi.loadData (new OnRequestListener () {




            @Override
            public void onBefore() {

            }

            @Override
            public void onSuccess() {
                if (deliverGoodsApi.list.size () == 0) {
                    return;
                }
                for (int i = 0, len = deliverGoodsApi.list.size (); i < len; i++) {
                    Object obj = deliverGoodsApi.list.get (i);
                    if (obj instanceof WmTmsNoticeHEntity) {
                        WmTmsNoticeHEntity wmTmsNoticeHEntity = (WmTmsNoticeHEntity) obj;
                        if (wmTmsNoticeHEntity.getReMobile ().equals ("") || wmTmsNoticeHEntity.getReCarno ().equals ("")) {

                        }else {
//                            delvAddr = wmTmsNoticeHEntity.getDelvAddr ();
                            String omNoticeId = wmTmsNoticeHEntity.getOmNoticeId ();
                            String s = wmTmsNoticeHEntity.getReMobile ().toString ();
                            String s1 = wmTmsNoticeHEntity.getReCarno ().toString ();
                            reMember = Double.valueOf (s);
                            reCarno = Double.valueOf (s1);
                            start (reMember,reCarno);
                            latLngsAllList.addAll (latLngsList);
                            allId.add (omNoticeId);
                            reCarnos.add (s1);
                            reMembers.add (s);
                        }
                    }
//                Log.e ("latLngsAllList",latLngsAllList.size ()+"");
//                Log.e ("allId",allId.size ()+"");
                }


            }

            @Override
            public void onFailure(Throwable error) {
            }

            @Override
            public void onNetWorkError() {

            }
        });
    }

    @Override
    public void fillData() {
        intData ();

    }

    @Override
    public void setListener() {
        toolbar.setNavigationOnClickListener (new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                finish ();
            }
        });
        //设置marker点击事件
        setMarkerClick ();
    }

    private void start(double v, double v1) {
        //获取坐标点(模拟，实际为后台返回坐标，需异步加载)
        getPoints (v, v1);
        //根据坐标点绘制Marker
        showLineMarker ();
        //比较选出集合中最大经纬度
        getMax ();
        //计算两个Marker之间的距离
        calculateDistance ();
        //根据距离判断地图级别
        getLevel ();
        //计算中心点经纬度，将其设为启动时地图中心
        setCenter ();

    }

    /**
     * 获取坐标点的方法
     */
    private void getPoints(double v, double v1) {
        //获取坐标点
        latLngsList = new ArrayList<LatLng> ();

        //模拟解析得到的坐标点
        final LatLng point = new LatLng (v, v1);

        // maxLatitude==39.963175;minLatitude==39.913375;maxLongitude==116.40227;minLongitude==116.200244

        latLngsList.add (point);

    }

    /**
     * 根据坐标点绘制Marker
     */
    private void showLineMarker() {
        //构建marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource (R.mipmap.icon_marka);

        for (int i = 0; i < latLngsList.size (); i++) {
            //构建MarkerOption，用于在地图上添加Marker
            option = new MarkerOptions ().icon (bitmap).position (latLngsList.get (i));
            //生长动画
            option.animateType (MarkerOptions.MarkerAnimateType.grow);
            //在地图上添加Marker，并显示
            mBaiduMap.addOverlay (option);
            //设置Marker覆盖物的ZIndex
            option.zIndex (i);
        }
    }

    /**
     * 比较选出集合中最大经纬度
     */
    private void getMax() {
        for (int i = 0; i < latLngsList.size (); i++) {
            double latitude = latLngsList.get (i).latitude;
            double longitude = latLngsList.get (i).longitude;
            latitudeList.add (latitude);
            longitudeList.add (longitude);
        }
        maxLatitude = Collections.max (latitudeList);
        minLatitude = Collections.min (latitudeList);
        maxLongitude = Collections.max (longitudeList);
        minLongitude = Collections.min (longitudeList);
    }

    /**
     * 计算两个Marker之间的距离
     */
    private void calculateDistance() {
        distance = GeoHasher.GetDistance (maxLatitude, maxLongitude, minLatitude, minLongitude);
    }

    /**
     * 根据距离判断地图级别
     */
    private void getLevel() {
        int zoom[] = {10, 20, 50, 100, 200, 500, 1000, 2000, 5000, 1000, 2000, 25000, 50000, 100000, 200000, 500000, 1000000, 2000000};
        Log.i ("info", "maxLatitude==" + maxLatitude + ";minLatitude==" + minLatitude + ";maxLongitude==" + maxLongitude + ";minLongitude==" + minLongitude);
        Log.i ("info", "distance==" + distance);
        for (int i = 0; i < zoom.length; i++) {
            int zoomNow = zoom[i];
            if (zoomNow - distance * 1000 > 0) {
                level = 18 - i + 6;
                //设置地图显示级别为计算所得level
                mBaiduMap.setMapStatus (MapStatusUpdateFactory.newMapStatus (new MapStatus.Builder ().zoom (level).build ()));
                break;
            }
        }
    }

    /**
     * 计算中心点经纬度，将其设为启动时地图中心
     */
    private void setCenter() {
        center = new LatLng ((maxLatitude + minLatitude) / 2, (maxLongitude + minLongitude) / 2);
        Log.i ("info", "center==" + center);
        MapStatusUpdate status1 = MapStatusUpdateFactory.newLatLng (center);
        mBaiduMap.animateMapStatus (status1, 500);
    }
    /**
     * 设置Marker点击事件
     */
    private void setMarkerClick() {
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                final LatLng ll = marker.getPosition();

                //动态生成一个view对象，用户在地图中显示InfoWindow
                final InfoView infoView = new InfoView(getApplicationContext());
                infoView.setBackgroundResource(R.drawable.button);
                for (int j = 0; j < latLngsAllList.size (); j++) {
                    final LatLng point = latLngsAllList.get (j);

                    GeoCoder geoCoder = GeoCoder.newInstance ();
                    // 设置反地理经纬度坐标,请求位置时,需要一个经纬度
                    geoCoder.reverseGeoCode (new ReverseGeoCodeOption ().location (point));

                    // 设置地址或经纬度反编译后的监听,这里有两个回调方法
                    geoCoder.setOnGetGeoCodeResultListener (new OnGetGeoCoderResultListener () {

                        @Override
                        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                                Toast.makeText (mContext, "找不到该地址" + point, Toast.LENGTH_SHORT).show ();
                            } else {
                                    infoView.setTv1 ( result.getAddress (), 14, Color.parseColor ("#999999"));
                            }
                        }

                        @Override
                        public void onGetGeoCodeResult(GeoCodeResult result) {
                            // 详细地址转换在经纬度
                            Toast.makeText (mContext, result.getAddress (), Toast.LENGTH_SHORT).show ();

                        }

                    });


                }

                infoView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        for (int j = 0; j < latLngsAllList.size(); j++) {
                            LatLng point = latLngsAllList.get(j);
                            String s = allId.get (j);
                            reCarnosId = reCarnos.get (j);
                            reMembersId = reMembers.get (j);
                            if (ll.equals(point)) {
                                myDialogUtils = new MyDialogUtils (DeliverGoodsDtActivity.this, R.layout.item_map, new int[]{R.id.tv_baidu, R.id.tv_tenxun, R.id.tv_cancel, R.id.tv_gaode});
                                myDialogUtils.setOnCenterItemClickListener (DeliverGoodsDtActivity.this);
                                myDialogUtils.show ();
//                                RouterUtils.openDeliverDetailsActivity (mContext,s);
//                                Toast.makeText(DeliverGoodsDtActivity.this, "point=" + point, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                });

                //初始化infoWindow，最后那个参数表示显示的位置相对于覆盖物的竖直偏移量，这里也可以传入一个监听器
                infoWindow = new InfoWindow(infoView, ll, -100);
                mBaiduMap.showInfoWindow(infoWindow);//显示此infoWindow
                //让地图以被点击的覆盖物为中心
                MapStatusUpdate status = MapStatusUpdateFactory.newLatLng(ll);
//                mBaiduMap.setMapStatus(status);
                //以动画方式更新地图状态，动画耗时 500 ms
                mBaiduMap.animateMapStatus(status, 500);
                return true;
            }
});
    }

    @Override
    public void OnCenterItemClick(MyDialogUtils dialog, View view) {
        switch (view.getId ()) {
            case R.id.tv_cancel:
                myDialogUtils.dismiss ();
                break;
            case R.id.tv_baidu:
                toHereByBaidu();
                break;
            case R.id.tv_tenxun:
                toHereByTengxun();
                break;
            case R.id.tv_gaode:
                toHereByGaode();
                break;
            default:
                break;
        }
    }
    public void toHereByGaode() {
        Intent intent;
        if (isAvilible(this, "com.autonavi.minimap")) {
            goToNaviActivity(this,"test",null,reMembersId,reCarnosId,"1","2");
        }else{
            ToastUtils.showShort ("您尚未安装高德地图");
//            Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
//            intent = new Intent(Intent.ACTION_VIEW, uri);
//            startActivity(intent);
        }
    }
    public void toHereByBaidu() {
        Intent intent;
        if (isAvilible(this, "com.baidu.BaiduMap")) {
            goToBaiduActivity(this,reMembersId,reCarnosId);
        }else{
            ToastUtils.showShort ("您尚未安装百度地图");
//            Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
//            intent = new Intent(Intent.ACTION_VIEW, uri);
//            startActivity(intent);
        }
    }

    public void toHereByTengxun() {
        Intent intent;
        if (isAvilible(this, "com.tencent.map")) {
            gotoTengxun(this,reMembersId,reCarnosId);
        }else{
            ToastUtils.showShort ("您尚未安装腾讯地图");
//            Uri uri = Uri.parse("market://details?id=com.tencent.map");
//            intent = new Intent(Intent.ACTION_VIEW, uri);
//            startActivity(intent);
        }
    }
    /**
     * 启动高德App进行导航

     *
     * @param sourceApplication 必填 第三方调用应用名称。如 amap
     * @param poiname 非必填 POI 名称
     * @param lat 必填 纬度
     * @param lon 必填 经度
     * @param dev 必填 是否偏移(0:lat 和 lon 是已经加密后的,不需要国测加密; 1:需要国测加密)
     * @param style 必填 导航方式(0 速度快; 1 费用少; 2 路程短; 3 不走高速；4 躲避拥堵；5 不走高速且避免收费；6 不走高速且躲避拥堵；7 躲避收费和拥堵；8 不走高速躲避收费和拥堵))
     */
    public static  void goToNaviActivity(Context context,String sourceApplication , String poiname , String lat , String lon , String dev , String style){
        StringBuffer stringBuffer  = new StringBuffer("androidamap://navi?sourceApplication=")
                .append(sourceApplication);
        if (!TextUtils.isEmpty(poiname)){
            stringBuffer.append("&poiname=").append(poiname);
        }
        stringBuffer.append("&lat=").append(lat)
                .append("&lon=").append(lon)
                .append("&dev=").append(dev)
                .append("&style=").append(style);

        Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
        intent.setPackage("com.autonavi.minimap");
        context.startActivity(intent);
    }

    /**
     * 启动百度App进行导航

     *
     * @param lat 必填 纬度
     * @param lon 必填 经度
     */
    public static  void goToBaiduActivity(Context context , String lat , String lon)
    {

        // 百度地图
        Intent naviIntent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("baidumap://map/geocoder?location=" + lat + "," + lon));
        context.startActivity(naviIntent);
    }

    /**
     * 启动腾讯地图App进行导航

     *
     * @param lat 必填 纬度
     * @param lon 必填 经度
     */
    public static  void gotoTengxun(Context context , String lat , String lon){

        // 腾讯地图
        Intent naviIntent = new Intent("android.intent.action.VIEW", android.net.Uri.parse("qqmap://map/routeplan?type=drive&from=&fromcoord=&to=目的地&tocoord=" + lat + "," + lon + "&policy=0&referer=appName"));
        context.startActivity(naviIntent);

    }
    /*
     * 检查手机上是否安装了指定的软件
     * @param context
     * @param packageName：应用包名
     * @return
             */
    public static boolean isAvilible(Context context, String packageName){
        //获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        //获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        //用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        //从pinfo中将包名字逐一取出，压入pName list中
        if(packageInfos != null){
            for(int i = 0; i < packageInfos.size(); i++){
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        //判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }
}
